﻿/**
//  SaveSettingCommand.cs
//  Marquee Moment
//  Copyright 2011 Systematix Technocrates. All rights reserved.
**/
using System;
using System.Runtime.InteropServices;
using EDSDKLib;
using MarqueeMoment.CameraController.Camera;

namespace MarqueeMoment.CameraController.Command
{
    public class SaveSettingCommand : Command
    {


        private EDSDKLib.EDSDK.EdsSaveTo saveTo;
        public SaveSettingCommand(CameraModel model, EDSDK.EdsSaveTo saveto)
            : base(model)
        {
            saveTo = saveto;
        }


        //// Execute a command.
        public override bool execute()
        {

            uint err = EDSDK.EDS_ERR_OK;
            bool @lock = false;

            //// You should do UILock when you send a command to camera models elder than EOS30D.

            if (base.model.isLegacy())
            {
                err = EDSDK.EdsSendStatusCommand(base.model.getCameraObject(), EDSDK.CameraState_UILock, 0);


                if (err == EDSDK.EDS_ERR_OK)
                {
                    @lock = true;

                }
            }

            ////Set destination of file save.

            if (err == EDSDK.EDS_ERR_OK)
            {

                IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(this.saveTo));
                Marshal.StructureToPtr(this.saveTo, ptr, false);

                err = EDSDK.EdsSetPropertyData(base.model.getCameraObject(), EDSDK.PropID_SaveTo, 0, Marshal.SizeOf(this.saveTo), this.saveTo);

                Marshal.FreeHGlobal(ptr);
            }


            if (@lock == true)
            {
                err = EDSDK.EdsSendStatusCommand(base.model.getCameraObject(), EDSDK.CameraState_UIUnLock, 0);

            }

            //// Notify Error.

            if (err != EDSDK.EDS_ERR_OK)
            {
                //// Retry when the camera replys deviceBusy.
                if (err == EDSDK.EDS_ERR_DEVICE_BUSY)
                {
                    base.model.notifyObservers(commandName.warn, err);
                    System.Threading.Thread.Sleep(500);
                    return false;

                }

                base.model.notifyObservers(commandName.errr, err);

            }

            return true;

        }

    }
}
